package com.dgut.legalservice.tool;

import com.dgut.legalservice.domain.contract.Contract;
import com.itextpdf.text.pdf.PdfReader;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.ooxml.extractor.POIXMLTextExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

//文件处理工具
public class FileTool {
    /**
     * @param uploadFile
     * @param request
     * @return 返回路径和文件名
     * @throws IOException
     */
    public static Map<String, String> fileUpload(MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        if (uploadFile == null) {
            return null;
        }
        //定义⽂件名
        String fileName = "";
        //1.获取⽂件名
        String uploadFileName = uploadFile.getOriginalFilename();
        int index = uploadFileName.lastIndexOf("\\");
        if (index != -1) {
            uploadFileName = uploadFile.getOriginalFilename().substring(index);
        }
        //3.把⽂件加上随机数，防⽌⽂件重复
        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        fileName = uuid + "_" + uploadFileName;
        System.out.println(fileName);
        ServletContext context = request.getServletContext();
        String basePath = context.getRealPath("/uploads");
        //3.解决同⼀⽂件夹中⽂件过多问题
        String datePath = new SimpleDateFormat("yyyy-MMdd").format(new Date());
        //4.判断路径是否存在
        File file = new File(basePath + "/" + datePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File file2 = new File(file, fileName);
        uploadFile.transferTo(file2);
        Map<String, String> map = new HashMap<String, String>() {{
            put("name", file2.getName());
            put("path", file2.getPath());
        }};
        return map;
    }

    /**
     * 下载
     *
     * @param path
     * @param name
     * @param request
     * @param response
     * @throws IOException
     */
    public static void downloadAttachment(String path, String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
            String realPath = request.getServletContext().getRealPath("/upload");
            File file = new File(path);
            InputStream fis = new FileInputStream(file);
            //4.将输⼊流的数据写出到输出流中
            String filename = name;
            if (name.indexOf('_') != -1) {
                filename = name.substring(name.indexOf('_') + 1);
            }
            response.setContentType(request.getServletContext().getMimeType(name));
            response.setHeader("content-disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "iso-8859-1"));
            ServletOutputStream sos = response.getOutputStream();
            byte[] buff = new byte[1024 * 8];
            int len = 0;
            while ((len = fis.read(buff)) != -1) {
            sos.write(buff, 0, len);
        }
        fis.close();
    }




    //定制合同内容转docx格式Word文档
    public static void downloadCustomContract(Contract contract, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType(request.getServletContext().getMimeType(contract.getName()+".docx"));
        response.setHeader("content-disposition", "attachment;filename=" + new String((contract.getName() + ".docx").getBytes("UTF-8"), "iso-8859-1"));
        ServletOutputStream sos = response.getOutputStream();

        XWPFDocument doc = DocumentTool.createDocument(contract);
        doc.write(sos);
    }

    //获取word文档页数
    public static int getDocxPages(String path) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(path);
        XWPFDocument docx = new XWPFDocument(fileInputStream);
        PdfOptions pdfOptions = PdfOptions.create();
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\temp.pdf");
        PdfConverter.getInstance().convert(docx, fileOutputStream, pdfOptions);
        fileOutputStream.close();
        fileInputStream.close();
        PdfReader reader = new PdfReader("E:\\temp.pdf");
        int pages= reader.getNumberOfPages();
        reader.close();
//        new File("D:\\temp.pdf").delete();
        return pages;
    }

    //读取word文档内容
    public static String getDocxText(String path) throws Exception{
        POIXMLTextExtractor extractor = new XWPFWordExtractor(POIXMLDocument.openPackage(path));
        String buffer = extractor.getText();
        extractor.close();
        return buffer;
    }
}